#include <memory>
#include <iostream>

#include "gui_client/gui_client.h"
#include <cstdlib>
#include "rclcpp/rclcpp.hpp"


gui::Client::Client() {

  node_ = rclcpp::Node::make_shared("gui_client");
  subscription_ = node_->create_subscription<std_msgs::msg::Int32>(
          "topic", 10, std::bind(
                  &Client::topic_callback, this, std::placeholders::_1));

  add_client_ = node_->create_client<example_interfaces::srv::AddTwoInts>("add_two_ints");
}

void gui::Client::topic_callback(std_msgs::msg::Int32::SharedPtr msg) const {
  RCLCPP_INFO(node_->get_logger(), "I heard: '%d'", msg->data);
  signal_pass_arg(msg->data, "This is String msg!");
}

boost::signals2::connection
gui::Client::connect_heartbeat_func(const V_slotType &slot) {
  return signal_heartbeat.connect(slot);
}

boost::signals2::connection
gui::Client::connect_pass_arg_func(const VIS_slotType &slot) {
  return signal_pass_arg.connect(slot);
}

int gui::Client::get_sum(int a, int b) {
  auto request = std::make_shared<example_interfaces::srv::AddTwoInts::Request>();
  request->a = a;
  request->b = b;
  int sum = -65535;

  while (!add_client_->wait_for_service(1s)) {
    if (!rclcpp::ok()) {
      RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "Interrupted while waiting for the service. Exiting.");
      return -65535;
    }
    RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "service not available, waiting again...");
  }

  auto result = add_client_->async_send_request(request);
  // Wait for the result.

  if (rclcpp::spin_until_future_complete(node_, result) ==
      rclcpp::FutureReturnCode::SUCCESS)
  {
    sum = result.get()->sum;
    RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "Sum: %ld", result.get()->sum);
  } else {
    RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "Failed to call service add_two_ints");
  }
  return sum;
}
